<template>
    <ul class="list">
        <li class="item"
            v-for="item of letters"
            :key="item"
            :ref="item"
            @click="handleLetterClick"
            @touchstart.prevent="handleTouchStart"
            @touchmove="handleTouchMove"
            @touchend="handleTouchEnd"
            >
            {{item}}
        </li>
    </ul>
</template>

<script>
export default {
    name: 'CityAlphabet',
    props: {
        cities: Object
    },
    computed: {
        // 设置一个数组用来存放所有的字母
        letters () {
            const letters = []
            // this.cities中的内容对应city.json中cities中内容，因为其中有两层，这里循环存入的是外层即所有字母
            for (let i in this.cities) {
                letters.push(i)
            }
            // 返回数组样式为['A','B','C',.....]
            return letters
        }
    },
    data () {
        return {
            touchStatus: false,
            startY: 0,
            timer: null
        }
    },
    updated () {
        // 当页面渲染完成，数据发生变化时触发
        this.startY = this.$refs['A'][0].offsetTop
    },
    methods: {
        handleLetterClick (e) {
            //           事件名    事件内容
            this.$emit('change', e.target.innerText)
        },
        handleTouchStart () {
            this.touchStatus = true
        },
        handleTouchMove (e) {
            if (this.touchStatus) {
                if (this.timer) {
                    clearTimeout(this.timer)
                }
                this.timer = setTimeout(() => {
                    // 获取A字母所在dom对应的offsetTop值，即距离顶端的高度
                    /*  但是这样写性能不太优，因为每次调用之后都需要进行一次计算，可以优化
                    const startY = this.$refs['A'][0].offsetTop */
                    // 减去的是青色头部区域的高度
                    const touchY = e.touches[0].clientY - 43 - 36
                    // 除以20是每个字母的高度，floor向下取整
                    const index = Math.floor((touchY - this.startY) / 20)
                    if (index >= 0 && index < this.letters.length) {
                        this.$emit('change', this.letters[index])
                    }
                }, 16)
            }
        },
        handleTouchEnd () {
            this.touchStatus = false
        }

    }
}
</script>

<style lang="stylus" scoped>
@import '~styles/varibles.styl'
    .list
        display: flex
        flex-direction: column
        justify-content: center
        position: absolute
        top: 1.58rem
        right: 0
        bottom: 0
        width: .4rem
        .item
            text-align: center
            line-height: .4rem
            color: $bgColor
</style>
